相信來到這個篇章的讀者,一定是受不了一直重新啟動服務的問題而來的
我們在編寫程式碼時最痛苦的就是,每改一行程式碼,服務就要重啟,不僅麻煩又耗時
幸運的是我們能使用 webpack HMR (Hot-Module Replacement),它能自動幫我們重新編譯,我們也就不需要再手動重啟服務重新編譯了
我們會使用 Nest CLI 來進行 Package 安裝以及配置
$ npm i --save-dev webpack-node-externals start-server-webpack-plugin
#OR
$ yarn add webpack-node-externals start-server-webpack-plugin
在根目錄中建立一個 webpack-hmr.config.js,將下面的程式碼貼上
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const StartServerPlugin = require('start-server-webpack-plugin');
module.exports = function(options) {
return {
...options,
entry: ['webpack/hot/poll?100', options.entry],
watch: true,
externals: [
nodeExternals({
allowlist: ['webpack/hot/poll?100'],
}),
],
plugins: [
...options.plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin([/\.js$/, /\.d\.ts$/]),
new StartServerPlugin({ name: options.output.filename }),
],
};
};
接著啟動 HMR ,在 main.ts 加入下方的程式碼
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();
最後修改 package.json 腳本
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js"
執行 yarn start:dev
將服務啟動
yarn start:dev
yarn run v1.22.4
$ nest build --webpack --webpackPath webpack-hmr.config.js
Info Webpack is building your sources...
Hash: 8a6fea9586bf0fb047f6
Version: webpack 4.44.1
Time: 6121ms
Built at: 09/23/2020 3:17:53 PM
Entrypoint main = main.js
[Nest] 23168 - 09/23/2020, 3:17:55 PM [NestFactory] Starting Nest application...
[Nest] 23168 - 09/23/2020, 3:17:55 PM [InstanceLoader] AppModule dependencies initialized +39ms
[Nest] 23168 - 09/23/2020, 3:17:55 PM [InstanceLoader] AuthorsModule dependencies initialized +1ms
[Nest] 23168 - 09/23/2020, 3:17:55 PM [InstanceLoader] GraphQLSchemaBuilderModule dependencies initialized +0ms
[Nest] 23168 - 09/23/2020, 3:17:55 PM [InstanceLoader] GraphQLModule dependencies initialized +1ms
只要程式碼一有變動,就會觸發 Hot Reload ,開始重新編譯,我們就不需要再重新啟動服務!
官方還有提供其他方式可以進行配置,不過我還沒實作過,所以這邊就不多做說明,有興趣的讀者可以到官網去參考參考